﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Xww.WindowsForm.Controls {
    public partial class RichTextBoxEx : RichTextBox {
    
        public RichTextBoxEx() {
            InitializeComponent();
            this.ContextMenuStrip = contextMenu;
            this.toolStripMenuItemUndo.Click += new EventHandler( (s,e)=>this.Undo() );
            this.toolStripMenuItemCopy.Click += new EventHandler( (s, e) => this.Copy() );
            this.toolStripMenuItemCut.Click += new EventHandler((s, e) => this.Cut());
            this.toolStripMenuItemPaste.Click +=new EventHandler((s,e)=>this.Paste(DataFormats.GetFormat(DataFormats.UnicodeText)));
            this.toolStripMenuItemDelete.Click += new EventHandler((s, e) => SendKeys.Send("{Del}"));
            this.toolStripMenuItemSelectAll.Click += new EventHandler((s,e)=>this.SelectAll());
        }

        protected override void OnKeyDown(KeyEventArgs e) {
            if (e.Control) {
                switch (e.KeyCode) {
                    case Keys.V:
                        base.Paste(DataFormats.GetFormat(DataFormats.UnicodeText));
                        e.Handled = true;
                        break;
                }
            }
            base.OnKeyDown(e);
        }

    ///<summary>表示文本框状态的快照</summary>
        public class Snap {
            public string Text { get; set; }
            public int SelectionStart { get; set; }
            public int SelectionLength { get; set; }
        }
    }
    public static class TextBoxBaseTool {
        public static RichTextBoxEx.Snap TakeSnap(this TextBoxBase control) {
            RichTextBoxEx.Snap rst = new RichTextBoxEx.Snap{ Text = control.Text, SelectionStart = control.SelectionStart, SelectionLength = control.SelectionLength };
            return rst;
        }
        public static void ResumeFromSnap(this TextBoxBase control, RichTextBoxEx.Snap snap) {
            if (snap == null) { return; }
            control.Text = snap.Text;
            control.SelectionStart = snap.SelectionStart;
            control.SelectionLength = snap.SelectionLength;
        }
    }
}
